package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

/**
 * @ClassName ImageDemo
 * @Description
 * @Author wangss
 * @date 2020.06.02 20:57
 * @Version 1.0
 */
public class PixelReaderDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        Image image = new Image("images/1.jpg");

        ImageView imageView = new ImageView(image);

        // 获取图形的像素
        PixelReader pixelReader = image.getPixelReader();
        int argb = pixelReader.getArgb(200, 200);
        int alpha = (argb >> 24) & 0xff;
        int red = (argb >> 16) & 0xff;
        int green = (argb >> 8) & 0xff;
        int blue = argb & 0xff;

        // 透明度
        System.out.println("alpha = " + alpha);
        System.out.println("red = " + red);
        System.out.println("green = " + green);
        System.out.println("blue = " + blue);

        Color color = pixelReader.getColor(0, 0);
        System.out.println("color = " + color.toString());


        System.out.println("------------------获取一块区域的像素-------------------");
        WritablePixelFormat<ByteBuffer> byteBgraPreInstance = PixelFormat.getByteBgraPreInstance();
        byte[] bytes = new byte[3 * 3 * 4];
        pixelReader.getPixels(0, 0, 3, 3, byteBgraPreInstance, bytes, 0, 3 * 4);
        for (int i = 0; i < bytes.length; i = i + 4) {
            int b = bytes[i] & 0xff;
            int g = bytes[i + 1] & 0xff;
            int r = bytes[i + 2] & 0xff;
            int a = bytes[i + 3] & 0xff;

            System.out.println("a = " + a + " r = " + r + " g = " + g + " b = " + b);
        }

        System.out.println("------------------获取一块区域的像素-------------------");
        WritablePixelFormat<IntBuffer> intArgbPreInstance = PixelFormat.getIntArgbPreInstance();
        int[] in = new int[9];
        pixelReader.getPixels(0, 0, 3, 3, intArgbPreInstance, in, 0, 3);
        for (int i = 0; i < in.length; i++) {
            int a = in[i] >> 24 & 0xff;
            int r = in[i] >> 16 & 0xff;
            int g = in[i] >> 8 & 0xff;
            int b = in[i] & 0xff;

            System.out.println("a = " + a + " r = " + r + " g = " + g + " b = " + b);
        }

        an.getChildren().add(imageView);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();
    }
}
